package com.utils;

import java.security.MessageDigest;
import java.security.SecureRandom;
import java.util.Random;

/**
 * SaltEncryptionUtil.java
 *
 * @author Liang 649355204@qq.com
 * CreateTime 2019/7/17 15:11
 */
public class SaltEncryptionUtil {

    /* 测试用
	public static void main(String[] args) {
		String str = "test";
		Encryption en = new Encryption();
		String salt = en.createSalt();
		str = salt+str;
		String sha512 = en.SHA512(str);
		System.out.println("salt="+salt);
		System.out.println("sha512="+sha512);
	}
	*/

    /** 生成盐(128个字符)  盐的长度应该等同于加密后字符串的长度 */
    public static final int SALT_LENGTH = 128;
    public static String createSalt() {
        char[] chars = "0123456789abcdefghijklmnopqrwtuvzxyzABCDEFGHIJKLMNOPQRSTUVWXYZ".toCharArray();
        char[] saltchars = new char[128];
        Random random = new SecureRandom();
        for (int i = 0; i < SALT_LENGTH; i++) {
            int n = random.nextInt(62);
            saltchars[i] = chars[n];
        }
        return new String(saltchars);
    }

    /** SHA512加密(128个字符) */
    public static String sha512(String pwd) {
        String shaPwd = null;
        if (pwd != null && pwd.length() > 0) {
            try {
                MessageDigest messageDigest = MessageDigest.getInstance("SHA-512");
                messageDigest.update(pwd.getBytes());
                byte[] byteBuffer = messageDigest.digest();
                StringBuilder strHexString = new StringBuilder();
                for (byte b : byteBuffer) {
                    String hex = Integer.toHexString(0xff & b);
                    if (hex.length() == 1) {
                        strHexString.append('0');
                    }
                    strHexString.append(hex);
                }
                shaPwd = strHexString.toString();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return shaPwd;
    }
}
